import datetime

from sqlalchemy import Column, Date, String, Index, or_, and_
from sqlalchemy.orm import Session

from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty


class JumpserverAudit(Base, SessionMixin):
    __tablename__ = 'jumpserver_audit'

    username = Column(String(50), nullable=False, comment="用户名称")
    hostname = Column(String(50), nullable=False, comment="主机名称")
    ip = Column(String(50), nullable=False, comment="IP地址")
    system_user = Column(String(50), nullable=False, comment="系统用户")
    create_date = Column(Date, default=datetime.date.today, nullable=False, comment="创建日期")

    __table_args__ = (
        Index('idx_jumpserver_audit_create_date', 'create_date'),
        Index('idx_jumpserver_audit_unique_date', 'username', 'hostname', 'system_user', 'create_date', unique=True),
    )

    def __repr__(self):
        return f"<uuid='{self.uuid}',username='{self.username}',hostname='{self.hostname},system_user='{self.system_user}'>"

    @classmethod
    def get_paginate(cls, db: Session, page: int, per_page: int, create_date: str, ):
        return db.query(cls).filter(cls.create_date == create_date).paginate(page=page, per_page=per_page)

    @classmethod
    def get_data_by_create_date(cls, db: Session, create_date: str):
        return db.query(cls).filter(cls.create_date == create_date).to_dict()

    @classmethod
    def get_search_paginate(cls, db: Session, page: int, per_page: int, create_date, search: str):
        # 排除主键字段信息组装模糊查询
        search_field = [col.like(f"%{search}%") for _, col in cls.__table__.c.items() if is_empty(col.primary_key)]
        data = db.query(cls).filter(or_(*search_field), and_(cls.create_date == create_date)).paginate(page=page,
                                                                                                       per_page=per_page)
        return data
